#include "NMPreHeader.h"
#include "NMBulletMgr.h"
#include "NMBullet.h"
#include "NMEnemyMgr.h"
#include "NMGlobalData.h"

static NMBulletMgr* gBulletMgr = NULL;

NMBulletMgr* NMBulletMgr::shared()
{
	FUNCTION_ENTER();

	if (gBulletMgr == NULL)
		gBulletMgr = new NMBulletMgr;

	FUNCTION_LEAVE();

	return gBulletMgr;
}

NMBulletMgr::NMBulletMgr()
{
	FUNCTION_ENTER();

	_batch = CCSpriteBatchNode::batchNodeWithFile("bullet.png");

	FUNCTION_LEAVE();
}

NMBulletMgr::~NMBulletMgr(void)
{
	FUNCTION_ENTER();

	FUNCTION_LEAVE();
}

void NMBulletMgr::addToLayer(CCLayer* layer)
{
	FUNCTION_ENTER();

	if (_batch->getParent())
		_batch->removeFromParentAndCleanup(false);
	layer->addChild(_batch, layerBullet);

	FUNCTION_LEAVE();
}

void NMBulletMgr::addNewBullet(CCPoint pos, float angle)
{
	FUNCTION_ENTER();

	NMGlobalData* globalData = NMGlobalData::shared();
	NMBulletType type = globalData->getCurrentBulletType();

	if (type != bulletType_Normal)
	{
		int count = globalData->getBulletCount(type);
		if (count > 0)
			globalData->addBulletCount(type, -1);
		else
		{
			type = bulletType_Normal;
			globalData->setCurrentBulletType(bulletType_Normal);
		}
	}

	NMBullet* bullet = new NMBullet(_batch, type);
	bullet->setPosition(pos);
	bullet->setAngle(angle);
	_batch->addChild(bullet);

	FUNCTION_LEAVE();
}

void NMBulletMgr::update(ccTime dt)
{
	FUNCTION_ENTER();

	CCArray* children = _batch->getChildren();
	CCObject* obj;
	CCARRAY_FOREACH(children, obj)
	{
		NMBullet* bullet = (NMBullet*)obj;

		if (bullet->isDestroied())
			continue;

		bullet->update(dt);

		bool isCollision = NMEnemyMgr::shared()->checkCollision(bullet);

		if (bullet->isCanBeDestroy() || isCollision)
		{
			bullet->destroy();
		}
	} // FOR_EACH

	FUNCTION_LEAVE();
}
